package com.autohammal.work;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.autohammal.ITask;
import com.autohammal.TaskListener;
import com.autohammal.task.TaskStatus;

/**
 * Work
 * 
 * @author dailey_dai Mar 3, 2011
 */
public class Work {
	public static final int DEFAULT_CAPACITY = 10;
	ExecutorService executorService = null;
	private int capacity = Integer.MIN_VALUE;
	private boolean runState = false;

	public Work(int capacity) {
		this.capacity = capacity;
	}

	public Work() {
	}

	public void setRunState(boolean runState) {
		this.runState = runState;
	}

	public boolean isRunState() {
		return runState;
	}

	public void stop() {
		executorService.shutdown();
	}

	public void stopNow() {
		executorService.shutdownNow();
	}

	public void start() {
		if (isRunState())
			return;

		if (executorService != null && executorService.isShutdown() == false) {
			executorService.shutdownNow();
		}
		if (capacity > Integer.MIN_VALUE) {
			executorService = Executors.newFixedThreadPool(capacity);
		} else {
			executorService = Executors.newCachedThreadPool();
			capacity = Integer.MIN_VALUE;
		}
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				setRunState(true);
				Logger.getLogger(getClass()).log(Level.DEBUG, "Work start.");
			}
		});

	}

	/**
	 * add a task to the queue wait to execute
	 * 
	 * @param task
	 */
	public Future<?> add(final ITask task) {
		return executorService.submit(new Runnable() {
			@Override
			public void run() {
				try {
					TaskListener tl = task.getTaskListener();
					if (tl != null)
						tl.onTaskBefore();
					task.executeTask();
					if (tl != null)
						tl.onTaskAfter();
					task.setTaskStatus(TaskStatus.COMPLETE);
				} catch (Exception e) {
					Logger.getLogger(getClass()).log(Level.ERROR, "add Task:"+task, e);
				}
			}
		});
	}
}
